<template>
  <div class="alarmmanage-main">

    <div class="header-main">
      <HeadMenu :activePage="activePanel"/>
    </div>
    <Card>
    <div style="margin-top: 10px;margin-left: 10px">
      <Row :gutter="4" >
<!--        <Col span="5"><Dateselect ref="eventTime" v-model="dateRange" placeholder="$t('date')"></Dateselect> </Col>-->
        <Col span="5"><DateTimeRangeSelect ref="eventTime" v-model="dateRange" :placeholder="$t('datetime')" width="100%"></DateTimeRangeSelect></Col>

        <Col span="5"><Input clearable :placeholder="$t('code')" v-model="queryParam.where.deviceCode"></Input> </Col>
        <Col span="5"><OrganizationTree ref="srhOrgSelect" width="200px" v-model="queryParam.where.orgId"></OrganizationTree> </Col>
        <Col span="5"><UserSelect ref="srhUserSelect" :placeholder="$t('select_people')" width="200px" v-model="queryParam.where.userId"></UserSelect> </Col>
<!--        <Col span="1"><Button type="primary" icon="ios-search" @click="getData">查询</Button></Col>-->
      </Row>
      <Row :gutter="4" >
        <Col span="5">
          <Select v-model="queryParam.where.alarmCate" :placeholder="$t('alarm_type')">
            <Option value=null>{{$t('all')}}</Option>
            <Option v-for="(item,index) in alarmCate" :key="index" :value="item.code">{{item.desc}}</Option>
          </Select>

        </Col>
        <Col span="5">
          <Select :placeholder="$t('dispose_status')" v-model="queryParam.where.dispose" >
            <Option value=null>{{$t('all')}}</Option>
            <Option value=1>{{$t('dispose_status_1')}}</Option>
            <Option value=0>{{$t('dispose_status_2')}}</Option>
          </Select>
        </Col>
        <Col span="5">
          <Input clearable :placeholder="$t('dispose_spec')" v-model="queryParam.where.disposeRemark"></Input>
        </Col>
        <Col span="5"><Button type="primary" icon="ios-search" @click="getData">{{$t('search')}}</Button></Col>
      </Row>
    </div>
    </Card>
    <Card>
      <div style="margin-top: 10px">
        <Table border :columns="columns" :data="tableData" :loading="tableLoading" :row-class-name="rowClassName">
          <template slot-scope="{ row, index }" slot="action">
            <Button v-if="row.dispose!=1" :disabled="!canDispose" type="primary" :Title="$t('dispose')" icon="md-hammer" style="margin-right: 3px" @click="dispose(row)"></Button>
            <span v-if="row.dispose==1" style="color: green" >{{$t('dispose_status_1')}}</span>
          </template>
          <template slot-scope="{ row, index }" slot="map">
            <Button :disabled="!(!!row.position)" type="default" :Title="$t('map')" icon="md-globe"
                    style="margin-right: 3px" @click="openMap(row)"></Button>
          </template>
        </Table>
        <TopnavPage v-model="queryParam.page" @changePage="changePage"></TopnavPage>
      </div>
    </Card>

    <AlarmManageDispose ref="alarmManageDispose"></AlarmManageDispose>
<!--    <Modal v-model="show" :title="title" :mask-closable="false" :footer-hide=true width="600px" :closable="false">
      <Form :model="row">
        <FormItem :label="$t('dispose_spec')">
          <Input clearable :placeholder="$t('dispose_spec')" v-model="row.disposeRemark" ></Input>
        </FormItem>
        <FormItem>
          <div style="float: right;">
            <Button style="margin-right: 10px" type="primary"  @click="save" >{{$t('save')}}</Button>
            <Button @click="close">{{$t('cancel')}}</Button>
          </div>
        </FormItem>
      </Form>
    </Modal>
    -->
    <Modal v-model="map.show" :title="map.tile" width="730px">
      <div id="alarmMap" ref="alarmMap" style="height:500px;width:700px;background-color: #FFFFFF"></div>
    </Modal>
  </div>
</template>
<script>
import DateTimeRangeSelect from "_c/topnav/DateTimeRangeSelect"
import TopnavPage from "_c/topnav/TopnavPage";
import OrganizationTree from "_c/topnav/OrganizationTree";
import Dateselect from "_c/topnav/date2select"
import UserSelect from "_c/topnav/UserModelSelect";
import StatisticsOnlineDetail from "@/view/Home/Moudle/statistics/StatisticsOnlineDetail";
import DeviceAlarm from "@/api/DeviceAlarm";
import HeadMenu from "@/view/Home/component/HeadMenu";
import MapInfo from "@/view/Home/map/maptools/data/MapInfo";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import {pointStyle, polygonStyle} from "@/view/Home/map/maptools/tool/style";
import {solveGps} from "@/view/Home/map/maptools/tool/GpsUtils";
import {Map, View} from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import AuthCheck from "@/api/AuthCheck";
import {apiResult} from "@/libs/util";
import AlarmManageDispose from "@/view/Home/Moudle/AlarmManageDispose"
export default {
  name: 'AlarmManage',
  components: {TopnavPage, OrganizationTree, DateTimeRangeSelect,UserSelect,HeadMenu,AlarmManageDispose },
  computed:{
    columns(){
      return [{ title: this.$t('operate'), key: 'action', width: 120, slot: 'action', align: 'center',ellipsis:true,tooltip:true,tooltipTheme:'light' },
        {title: this.$t('code'), key: 'deviceCode', sortable: true,width: 200,align: 'center',ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('name'), key: 'deviceName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('organization'), key: 'shortName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('personnel'), key: 'userName', sortable: true, width: 175,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('time'), key: 'alarmTime', sortable: true,width: 200,align: 'center',ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('type'), key: 'alarmCateDesc', sortable: true, width: 175,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        /*{title: this.$t('note'), key: 'alarmDescription', sortable: true, width: 150,ellipsis:true,tooltip:true,tooltipTheme:'light'},*/
        {title: this.$t('location'), key: 'position', sortable: true, width: 250,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: '', key: '', sortable: true, width: 80,slot:"map"},
        {title: this.$t('dispose_spec'), key: 'disposeRemark', sortable: true, width: 230,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('dispose_by'), key: 'disposeBy', sortable: true, width: 150,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('dispose_time'), key: 'disposeTime', sortable: true, width: 150,ellipsis:true,tooltip:true,tooltipTheme:'light'}]
    }
  },
  data() {
    return {
      canDispose:false,
      map:{
        tile: "",
        show:false,
        obj:null,
        mapInfo:null,
        customLayers:{
          layerVector: null,
          sourceVector: null,
        },
      },
      title: "",
      alarmCate:[],
      api: new DeviceAlarm(),
      activePanel:0,

      dateRange: [],
      queryParam: {
        page: {
          pages: 1,
          size: 15,
          total: 0,
          current: 1,
        },
        where: {
          keyword: null,
          deviceId: null,
          fromTime: null,
          toTime: null,
          userId: null,
          orgId: null,
          deviceCode: null,
          isGroupBy: false,
          dispose:-1,
          disposeRemark:null,
          alarmCate:null
        },
      },
      tableData: [],
      tableLoading: false

    }
  },
  methods: {
    openMap(row) {
      this.map.show = true;
      if (this.map.show) {
        this.$nextTick(() => {
          this.initMap(row);
        })
      }
    },
    initMap(row){
      if (!!this.map.mapObj){
        this.map.mapObj.setTarget(null);
        this.map.mapObj.dispose()
        this.map.mapObj = null;
        this.map.customLayers.layerVector = null;
        this.map.customLayers.sourceVector = null;
      }
      this.map.mapInfo = new MapInfo().get();
      this.map.customLayers.layerVector =  new LayerVector();
      this.map.customLayers.sourceVector =  new SourceVector();
      this.map.customLayers.layerVector.setSource(this.map.customLayers.sourceVector);
      this.map.customLayers.layerVector.setStyle(polygonStyle);
      const that = this;

      const pos1 = row.position.split(",");
      let pos = [];
      pos.push(parseFloat(pos1[0]));
      pos.push(parseFloat(pos1[1]));
      //坐标系转换
      const gpsData = solveGps(row.coordinateSystem,pos[1],pos[0]);
      if (!!gpsData){
        pos[0]=gpsData.lon;
        pos[1]=gpsData.lat;
      }
      that.map.mapObj = new Map({
        target: "alarmMap", // 指向对象
        layers: [
          new TileLayer({
            source: new XYZ({
              //url: "http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}"
              url: that.map.mapInfo.sub.url[0]
            }),
          })
        ],
        loadTilesWhileAnimating: true,//支持动画
        view: new View({
          projection: this.map.mapInfo.projection, //"EPSG:4326",
          center: pos,
          zoom: 16,
        })
      });

      that.map.mapObj.addLayer(that.map.customLayers.layerVector);

      const point = new Feature({
        geometry: new Point(pos),
      });

      point.setStyle(pointStyle({online:"1",title:row.deviceName}));
      this.map.customLayers.sourceVector.addFeature(point);
    },

    close(){
      this.show=false;
    },
    /**
     * 处置
     */
    dispose(row){
      this.$refs.alarmManageDispose.openDialog(row,this.getData) //此处不能的括号
    },
    changePage() {
      this.getData()
    },
    getData() {
      this.tableLoading = true;
      if (this.queryParam.where.dispose == -1){this.queryParam.where.dispose=null}
      /** 生成查询条件 */
      if (!(this.dateRange == null || this.dateRange.length < 2 || this.dateRange[0] == "")) {
        this.queryParam.where.fromTime = this.dateRange[0];
        this.queryParam.where.toTime = this.dateRange[1];
      }
      this.api.queryPage(JSON.stringify(this.queryParam)).then(res => {
         this.tableData = [];
         apiResult(res.data,false,result=>{
          this.queryParam.page.total = result.data.total;
          this.tableData = result.data.records;
          if (!!this.tableData && this.tableData.length > 0){
            this.tableData.forEach(item=>{
              item.alarmCateDesc = this.$t("alarm_cate_" + item.alarmCate);
            })
          }
        });
        this.tableLoading = false;
      })
    },

    getDeviceAlarmCate(){
      this.api.getDeviceAlarmCate().then(res => {
        this.alarmCate = [];
        apiResult(res.data,false,result=>{
          this.alarmCate = result.data
          if (!!this.alarmCate && this.alarmCate.length > 0){
            this.alarmCate.forEach(item=>{
              item.desc = this.$t('alarm_cate_' + item.code)
            })
          }
          this.getData()
        })
      })
    },
    rowClassName (row, index) {
      if (row.dispose != 1) {
        return 'demo-table-undispose-row';
      } else {
        return '';
      }
      //demo-table-disposed-row
      return '';
    },
  },
  mounted() {
    this.activePanel=6;
    /** 为了显示用，调置默认值 */
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    start.setMilliseconds(0);
    end.setHours(23);
    end.setMinutes(59);
    end.setSeconds(59);
    end.setMilliseconds(999);

    this.dateRange = [start, end];
    this.getDeviceAlarmCate()

    this.canDispose = new AuthCheck().alarmManageDispose();
  }
}
</script>
<style lang="less">
.alarmmanage-main {
  width: 100%;
  height: 100%;
  background-color: #eaeef5;
  display: flex;
  flex-direction: column;
  .header-main {
    width: 100%;
    height: 64px;
    display: flex;
   // border: 0.5 px solid #fcfdff;
  }

}
.ivu-table .demo-table-disposed-row td{
  background-color: #2db7f5;
  color: #fff;
}
.ivu-table .demo-table-undispose-row td{
  background-color: #d0d6da;
  color: #0000ff;
}
</style>
